package org.heart.thirdService.AIServiceAPI.tools;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import dev.langchain4j.agent.tool.Tool;
import dev.langchain4j.data.document.Document;
import dev.langchain4j.data.document.loader.FileSystemDocumentLoader;
import dev.langchain4j.data.segment.TextSegment;
import dev.langchain4j.model.openai.OpenAiChatModel;
import dev.langchain4j.rag.content.retriever.EmbeddingStoreContentRetriever;
import dev.langchain4j.service.AiServices;
import dev.langchain4j.store.embedding.EmbeddingStoreIngestor;
import dev.langchain4j.store.embedding.inmemory.InMemoryEmbeddingStore;
import lombok.extern.slf4j.Slf4j;
import org.heart.common.CommonResult;
import org.heart.entity.dto.CityCodeList;
import org.heart.service.ICityCodeListService;
import org.heart.service.impl.CityCodeListServiceImpl;
import org.heart.thirdService.AIServiceAPI.service.AisServices;
import org.heart.thirdService.hefengAPI.req.HourlyWeather;
import org.heart.thirdService.hefengAPI.service.HeFengApiService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;

@Component
@Slf4j
public class WeatherTool {

    @Resource
    private OpenAiChatModel openAiChatModel;

    @Resource
    private ICityCodeListService iCityCodeListService;

    @Resource
    private HeFengApiService heFengApiService;

    @Tool("获取指定城市今天的天气信息，参数 city 是城市名称，例如：'北京', '上海', '南阳'")
    public String getTodayWeather(String city) {
        log.info("获取城市：{}，今天的天气信息工具调用！",city);
        return callWeatherApi(city);
    }


    private String callWeatherApi(String city) {
        QueryWrapper<CityCodeList> qw = new QueryWrapper<>();
        qw.eq("location_name_zh",city);
        List<CityCodeList> list =  iCityCodeListService.list(qw);
        if(list.size()==0){
            return "该城市信息目前并未建档，无法获取该城市天气信息";
        }

        String locationId = list.get(0).getLocationId();

        System.out.println("locationId==="+locationId);

        List<HourlyWeather> lists = heFengApiService.getHourDuanWeather(locationId);

        String weatherText = formatHourlyWeatherList(lists);

        AisServices assistant = AiServices.create(AisServices.class,openAiChatModel);

        // 构造提示语
        String prompt = """
        请根据以下逐小时天气预报数据，简洁地总结出该城市今日的天气概况，并尽量包括以下几点内容：
        1. 天气状况（例如晴、阴、小雨等）；
        2. 温度范围（最高温、最低温）；
        3. 风力情况（风向+风力）；
        4. 湿度；
        5. 如有降雨或强对流天气，请给出提示；
        6. 最后给出简要的出行建议（如需带伞、防晒、注意交通等）；

        以下是 %s 的小时级天气数据：
        %s
        """.formatted(city, weatherText);

        String result = assistant.chat1(prompt);

        System.out.println("result=====");
        System.out.println(result);

        return result;
    }

    /**
     * 集成 RAG 系统
     * 获取城市 location_id 信息
     */
    public String getLocationId(String city) {
        String projectRootPath = new File("").getAbsolutePath();
        String filePath = projectRootPath + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator + "static";

        List<Document> documents = FileSystemDocumentLoader.loadDocuments(filePath);
        InMemoryEmbeddingStore<TextSegment> embeddingStore = new InMemoryEmbeddingStore<>();
        System.out.println("embeddingStore=="+embeddingStore);

        EmbeddingStoreIngestor.ingest(documents, embeddingStore);

        System.out.println("embeddingStore=="+embeddingStore);

        AisServices assistant = AiServices.builder(AisServices.class)
                .chatModel(openAiChatModel)
                .contentRetriever(EmbeddingStoreContentRetriever.from(embeddingStore))
                .build();

        String message = assistant.chat1(
                "请从数据中精确查询 `location_name_zh` 字段值为 '" + city + "' 的城市记录，并返回location_id 值,格式为：location_id=123 如果该城市不存在的话，就返回null "
        );
        return message;
    }

    public String formatHourlyWeatherList(List<HourlyWeather> weatherList) {
        StringBuilder sb = new StringBuilder();
        for (HourlyWeather weather : weatherList) {
            sb.append(String.format("时间：%s，温度：%s°C，天气：%s，风向：%s，风速：%skm/h，降水：%smm\n",
                    weather.getFxTime(), weather.getTemp(), weather.getText(),
                    weather.getWindDir(), weather.getWindSpeed(), weather.getPrecip()));
        }
        return sb.toString();
    }
}
